var app = getApp();
var WxParse = require('../../lib/wxParse/wxParse.js');
var util = require('../../utils/util.js');
var api = require('../../config/api.js');

Page({
  data: {
    lists: [{
      value:''
    }],
    winHeight: "",
    id: '',
    goods: {},
    gallery: [],
    specificationList: [],
    productList: [],
    relatedGoods: [],
    cartGoodsCount: 0,
    userHasCollect: 0,
    number: 1,
    checkedSpecText: '请选择规格数量',
    openAttr: false,
    noCollectImage: "/static/images/icon_collect.png",
    hasCollectImage: "/static/images/icon_collect_checked.png",
    collectBackImage: "/static/images/icon_collect.png",
    guige:[
      {id:1, name:'01-05'},
      {id:2, name:'06-10'},
      {id:3, name:'11-15'},
      {id:4, name:'16-20'}
    ],
    pm:[
      0,0,0,0,0
    ],
    color:[
      { id: 5, name: '红'},
      { id: 6, name: '橙'},
      { id: 7, name: '黄'},
      { id: 8, name: '绿'}
    ],
    listData:[]
  },
  onAddPhone: function () {
    var lists = this.data.lists;
    var newData = { value: ''};
    if (lists.length >= 3) {
      Dialog.alert({
        message: '最多再增加2个输入框'
      });
      return;
    }
    lists.push(newData);
    this.setData({
      lists: lists,
    })
  },
  delList: function () {
    var lists = this.data.lists;
    if (lists.length<=1){
      Dialog.alert({
        message: '不能删除默认输入框'
      });
      return;
    }
    lists.pop();  
    this.setData({
      lists: lists,
    })
  }, 
  bindPhoneDataChang0: function (e){
    var up = "lists[" + 0 + "].value";
    this.setData({
      [up]: e.detail
    })
  } , 
  bindPhoneDataChang1: function (e) {
    var up = "lists[" + 1 + "].value";
    this.setData({
      [up]: e.detail
    })
  } ,
  bindPhoneDataChang2: function (e) {
    var up = "lists[" + 2 + "].value";
    this.setData({
      [up]: e.detail
    })
  },


  getGoodsInfo: function () {
    let that = this;
    util.request(api.GoodsDetail, { id: that.data.id }).then(function (res) {
      if (res.errno === 0) {
        that.setData({
          goods: res.data.info,
          gallery: res.data.gallery,
          guige: res.data.guigeList,
          color: res.data.colorList
        });
        WxParse.wxParse('goodsDetail', 'html', res.data.info.goods_desc, that);
      }
    });

  },
  getGoodsRelated: function () {
    let that = this;
    util.request(api.GoodsRelated, { id: that.data.id }).then(function (res) {
      if (res.errno === 0) {
        that.setData({
          relatedGoods: res.data.goodsList,
        });
      }
    });

  },
  clickSkuValue: function (event) {
    let that = this;
    let specNameId = event.currentTarget.dataset.nameId;
    let specValueId = event.currentTarget.dataset.valueId;

    //判断是否可以点击

    //TODO 性能优化，可在wx:for中添加index，可以直接获取点击的属性名和属性值，不用循环
    let _specificationList = this.data.specificationList;
    for (let i = 0; i < _specificationList.length; i++) {
      if (_specificationList[i].specification_id == specNameId) {
        for (let j = 0; j < _specificationList[i].valueList.length; j++) {
          if (_specificationList[i].valueList[j].id == specValueId) {
            //如果已经选中，则反选
            if (_specificationList[i].valueList[j].checked) {
              _specificationList[i].valueList[j].checked = false;
            } else {
              _specificationList[i].valueList[j].checked = true;
            }
          } else {
            _specificationList[i].valueList[j].checked = false;
          }
        }
      }
    }
    this.setData({
      'specificationList': _specificationList
    });
    //重新计算spec改变后的信息
    this.changeSpecInfo();

    //重新计算哪些值不可以点击
  },

  //获取选中的规格信息
  getCheckedSpecValue: function () {
    let checkedValues = [];
    let _specificationList = this.data.specificationList;
    for (let i = 0; i < _specificationList.length; i++) {
      let _checkedObj = {
        nameId: _specificationList[i].specification_id,
        valueId: 0,
        valueText: ''
      };
      for (let j = 0; j < _specificationList[i].valueList.length; j++) {
        if (_specificationList[i].valueList[j].checked) {
          _checkedObj.valueId = _specificationList[i].valueList[j].id;
          _checkedObj.valueText = _specificationList[i].valueList[j].value;
        }
      }
      checkedValues.push(_checkedObj);
    }

    return checkedValues;

  },
  //根据已选的值，计算其它值的状态
  setSpecValueStatus: function () {

  },
  //判断规格是否选择完整
  isCheckedAllSpec: function () {
    return !this.getCheckedSpecValue().some(function (v) {
      if (v.valueId == 0) {
        return true;
      }
    });
  },
  getCheckedSpecKey: function () {
    let checkedValue = this.getCheckedSpecValue().map(function (v) {
      return v.valueId;
    });

    return checkedValue.join('_');
  },
  changeSpecInfo: function () {
    let checkedNameValue = this.getCheckedSpecValue();

    //设置选择的信息
    let checkedValue = checkedNameValue.filter(function (v) {
      if (v.valueId != 0) {
        return true;
      } else {
        return false;
      }
    }).map(function (v) {
      return v.valueText;
    });
    if (checkedValue.length > 0) {
      this.setData({
        'checkedSpecText': checkedValue.join('　')
      });
    } else {
      this.setData({
        'checkedSpecText': '请选择规格数量'
      });
    }

  },
  getCheckedProductItem: function (key) {
    return this.data.productList.filter(function (v) {
      if (v.goods_specification_ids.indexOf(key) > -1) {
        return true;
      } else {
        return false;
      }
    });
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    this.setData({
      id: options.id
      // id: 1181000
    });
    var that = this;
    this.getGoodsInfo();
    var that = this
    //  高度自适应
    wx.getSystemInfo({
      success: function (res) {
        var clientHeight = res.windowHeight,
          clientWidth = res.windowWidth,
          rpxR = 750 / clientWidth;
        var calc = clientHeight * rpxR - 100;
        that.setData({
          winHeight: calc
        });
      }
    });
  },
  onReady: function () {
    // 页面渲染完成

  },
  onShow: function () {
    // 页面显示

  },
  onHide: function () {
    // 页面隐藏

  },
  onUnload: function () {
    // 页面关闭

  },
  switchAttrPop: function () {
    if (this.data.openAttr == false) {
      this.setData({
        openAttr: !this.data.openAttr,
        collectBackImage: "/static/images/detail_back.png"
      });
    }
  },
  closeAttrOrCollect: function () {
    let that = this;
    if (this.data.openAttr) {
      this.setData({
        openAttr: false,
      });
      if (that.data.userHasCollect == 1) {
        that.setData({
          'collectBackImage': that.data.hasCollectImage
        });
      } else {
        that.setData({
          'collectBackImage': that.data.noCollectImage
        });
      }
    } else {
      //添加或是取消收藏
      util.request(api.CollectAddOrDelete, { typeId: 0, valueId: this.data.id }, "POST", "application/json")
        .then(function (res) {
          let _res = res;
          if (_res.errno == 0) {
            if ( _res.data.type == 'add') {
              that.setData({
                'collectBackImage': that.data.hasCollectImage
              });
            } else {
              that.setData({
                'collectBackImage': that.data.noCollectImage
              });
            }

          } else {
            wx.showToast({
              image: '/static/images/icon_error.png',
              title: _res.errmsg,
              mask: true
            });
          }

        });
    }

  },
  openCartPage: function () {
    wx.switchTab({
      url: '/pages/cart/cart',
    });
  },

  /**
   * 直接购买
   */
  buyGoods: function () {
    var that = this;
    if (this.data.openAttr == false) {
      //打开规格选择窗口
      this.setData({
        openAttr: !this.data.openAttr,
        collectBackImage: "/static/images/detail_back.png"
      });
    } else {

      if(this.data.listData.length==0){
        wx.showToast({
          title: '购买列表为空!!!',
          icon: 'fail',
          duration: 5000,
          mask: true
        });
        return;
      }
      // 直接购买商品
      util.request(api.BuyAdd, { goodsId: this.data.goods.goods_id, listData: this.data.listData}, "POST",'application/json')
        .then(function (res) {
          let _res = res;
          if (_res.errno == 0) {
            that.setData({
              openAttr: !that.data.openAttr,
            });
            wx.navigateTo({
              url: '/pages/ucenter/orderDetail/orderDetail?orderNo='+_res.data.orderNo,
            })
          } else {
            wx.showToast({
              image: '/static/images/icon_error.png',
              title: _res.errmsg,
              mask: true
            });
          }

        });

    }
  },

  cutNumber: function () {
    this.setData({
      number: (this.data.number - 1 > 1) ? this.data.number - 1 : 1
    });
  },
  addNumber: function () {
    this.setData({
      number: this.data.number + 1
    });
  },
    setDefSpecInfo: function (specificationList) {
        //未考虑规格联动情况
        let that = this;
        if (!specificationList)return;
        for (let i = 0; i < specificationList.length;i++){
            let specification = specificationList[i];
            let specNameId = specification.specification_id;
            //规格只有一个时自动选择规格
            if (specification.valueList && specification.valueList.length == 1){
                let specValueId = specification.valueList[0].id;
                that.clickSkuValue({ currentTarget: { dataset: { "nameId": specNameId, "valueId": specValueId } } });
            }
        }
        specificationList.map(function(item){

        });

    },
    guige : function(e) {
      this.setData({
        gid: e.currentTarget.dataset.index,
        gname: e.currentTarget.dataset.name,
        gindex: e.currentTarget.dataset.current,
      })
    },
    // pmF1 :function(e) {
    //   var pmF1Value = e.detail.value;
    //   this.data.pm[0] = pmF1Value;
    // },
    // pmF2 :function(e) {
    //   var pmF1Value = e.detail.value;
    //   this.data.pm[1] = pmF1Value;
    // },
    // pmF3 :function(e) {
    //   var pmF1Value = e.detail.value;
    //   this.data.pm[2] = pmF1Value;
    // },
    // pmF4 :function(e) {
    //   var pmF1Value = e.detail.value;
    //   this.data.pm[3] = pmF1Value;
    // },
    // pmF5 :function(e) {
    //   var pmF1Value = e.detail.value;
    //   this.data.pm[4] = pmF1Value;
    // },
    color : function(e) {
      this.setData({
        cid: e.currentTarget.dataset.index,
        cname: e.currentTarget.dataset.name,
        cindex: e.currentTarget.dataset.current,
      })
    },
    addLine : function() {

      var guige_id = this.data.gid;
      var guige_name = this.data.gname;
      // var pmArray = this.data.pm;
      // console.log(pmArray);
      // var pmStr = "";
      // for(var pmIndex = 0; pmIndex < pmArray.length; pmIndex++) {
      //   var pmItem = pmArray[pmIndex];
      //   if(undefined === pmItem || "" == pmItem) {
      //     wx.showToast({
      //       title: '请填写齐全配码元素!!!',
      //       icon: 'fail',
      //       duration: 3000,
      //       mask: true
      //     });
      //     return;
      //   }
      //   if(pmIndex == (pmArray.length-1)) {
      //     pmStr += pmItem;
      //   } else {
      //     pmStr += pmItem + "-";
      //   }
      // }

      if(undefined === guige_id) {
        wx.showToast({
          title: '请选择产品!!!',
          icon: 'fail',
          duration: 3000,
          mask: true
        });
        return;
      }

      // var color_id = this.data.cid;
      // var color_name = this.data.cname;
      // if(undefined === color_id) {
      //   wx.showToast({
      //     title: '请选择颜色!!!',
      //     icon: 'fail',
      //     duration: 5000,
      //     mask: true
      //   });
      //   return;
      // }

      var number_tmp = this.data.number + "";

      //{"code":"01-05","text":"红","type":"1","boxCount":"1", "optTyp":"del"},
      var orderMsg = new Object();
      orderMsg.code = guige_id;//产品编号
      orderMsg.text = guige_name;//产品描述
      // orderMsg.type = pmStr;
      orderMsg.boxCount = number_tmp;
      orderMsg.optTyp = "点击删除";
      this.data.listData.push(orderMsg);
      this.setData({
        listData: this.data.listData
      });
    },
    delLine: function(e) {
      var code = e.currentTarget.dataset.code;
      var text = e.currentTarget.dataset.text;
      var boxcount = e.currentTarget.dataset.boxcount;
      var current = e.currentTarget.dataset.current;
      var orderList = this.data.listData;
      console.log(current);
      orderList.splice(current, 1);
      this.setData({
        listData: this.data.listData
      });
      console.log(orderList);
    }
})